package com.vsd.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cyz.domain.CateRecommend;
import com.demo.dialet.PaginationSupport;
import com.demo.util.SqlUtils;
import com.vsd.daoEx.model.CateRecommendEx;
import com.vsd.repository.CateRecommendRepository;
import com.vsd.service.CateRecommendService;

@Service
@Transactional
public class CateRecommendServiceImpl implements CateRecommendService {

	@SuppressWarnings("unused")
	private static final Logger LOGGER = LoggerFactory
			.getLogger(CateRecommendServiceImpl.class);
	
	@Autowired
	JdbcTemplate jdbcTemplate;
	
	@Autowired
	private CateRecommendRepository cateRecommendRepository;
	
	@Override
	public CateRecommend save(CateRecommend r){
		return cateRecommendRepository.save(r);
	}
	
	@Override
	public CateRecommend findOne(String id){
		return cateRecommendRepository.findOne(id);
	}
	
	@Override
	public void delById(String id){
		cateRecommendRepository.delete(id);
	}
	
	@Override
	public int countByCode(String code,String areaCode){
		return cateRecommendRepository.countByCode(code, areaCode);
	}
	
	@Override
	public int updateByPrimaryKeySelective(CateRecommend r){
		String sql=null;
		try {
			sql = SqlUtils.update(r, true, " where id = '"+r.getId()+"'");
		} catch (Exception e) {
			return 0;
		}
		return jdbcTemplate.update(sql);
	}

	@Override
	public List<CateRecommendEx> selectExList(String areaCode) {
		// TODO Auto-generated method stub
		String sql = "select cr.*,c.name as cityName from c_cate_recommend cr "
				+ "left join f_city c on cr.area_code = c.code where 1=1";
		if(StringUtils.isNotBlank(areaCode)){
			sql+=" and cr.area_code = '"+areaCode+"' order by cr.sort desc";
		}else{
			sql+=" order by cr.create_time desc,cr.sort desc";
		}
		
		int c = jdbcTemplate.queryForObject("select count(1) from ("+ sql+") a_cnt", Integer.class);
		PaginationSupport.getContext().setTotalCount(c);
		
		sql+=" limit "+(PaginationSupport.getContext().getStartRowNo()-1)+","+PaginationSupport.getContext().getPageLength();
		
		List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
		List<CateRecommendEx> exList = new ArrayList<>();
		for (Map<String, Object> map : maps) {
			CateRecommendEx ex = new CateRecommendEx();
			SqlUtils.transMap2Bean2(map, ex);
			exList.add(ex);
		}
		return exList;
	}

	 

	
}
